import 'dart:io';
import 'dart:typed_data';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:image/image.dart' as img;
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import '../models/question.dart';

enum WordExportType {
  questionsOnly,
  questionsWithAnswers
}

class WordExportUtil {
  // 导出题目到Word文档
  static Future<String?> exportQuestionsToWord(
    List<Question> questions, {
    required WordExportType exportType,
  }) async {
    try {
      // 创建Word文档内容
      String wordContent = await _generateWordContent(questions, exportType);
      
      // 根据题目类型确定模块名称
      String moduleName = '';
      if (questions.isNotEmpty) {
        String type = questions[0].type;
        
        // 根据题目类型确定模块名称
        switch (type) {
          case 'logical_reasoning':
            moduleName = '逻辑推理';
            break;
          case 'quantitative_relation':
            moduleName = '数量关系';
            break;
          case 'politics':
            moduleName = '时政';
            break;
          case 'common_sense':
            moduleName = '常识';
            break;
          case 'verbal_comprehension':
            moduleName = '言语理解';
            break;
          case 'data_analysis':
            moduleName = '资料分析';
            break;
          default:
            moduleName = '题库';
            break;
        }
      } else {
        moduleName = '题库';
      }
      
      // 根据导出类型确定文件名前缀
      String filePrefix = exportType == WordExportType.questionsOnly ? '题目导出' : '题目答案解析导出';
      
      // 根据平台确定导出路径
      String dirPath;
      if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
        // 桌面平台使用固定路径
        dirPath = 'D:\\000\\my-web\\学习宝库\\$moduleName';
        
        // 确保目录存在
        final directory = Directory(dirPath);
        if (!await directory.exists()) {
          await directory.create(recursive: true);
        }
        
        // 使用指定的目录路径
        final path = '$dirPath\\${filePrefix}_${DateTime.now().millisecondsSinceEpoch}.docx';
        final file = File(path);
        
        // 写入文件
        await file.writeAsString(wordContent, encoding: utf8);
        
        print('Word文件已导出到: $path');
        return path;
      } else {
        // 移动平台使用Download/考试宝目录
        try {
          // 请求存储权限
          var status = await Permission.storage.request();
          if (!status.isGranted) {
            throw Exception('需要存储权限才能导出文件');
          }
          
          // 获取外部存储目录
          final directory = await getExternalStorageDirectory();
          if (directory == null) {
            throw Exception('无法获取外部存储目录');
          }
          
          // 获取Download目录 - 内部存储
          final downloadDir = Directory('${directory.path.split('Android')[0]}Download/学习宝库/$moduleName');
          print('导出模块名称: $moduleName');
          dirPath = downloadDir.path;
          
          // 确保目录存在
          if (!await downloadDir.exists()) {
            await downloadDir.create(recursive: true);
          }
          
          // 使用指定的目录路径
          final path = '$dirPath/${filePrefix}_${DateTime.now().millisecondsSinceEpoch}.docx';
          final file = File(path);
          
          // 写入文件
          await file.writeAsString(wordContent, encoding: utf8);
          
          print('移动平台Word文件导出路径: $path');
          return path;
        } catch (e) {
          print('设置移动平台导出路径失败: $e');
          throw Exception('设置导出路径失败: $e');
        }
      }
    } catch (e) {
      print('导出题目到Word失败: $e');
      throw Exception('导出失败: $e');
    }
  }
  
  // 生成Word文档内容
  static Future<String> _generateWordContent(List<Question> questions, WordExportType exportType) async {
    StringBuffer content = StringBuffer();
    
    // 添加Word文档头部
    content.writeln('<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">');
    content.writeln('<head>');
    content.writeln('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">');
    content.writeln('<meta name="ProgId" content="Word.Document">');
    content.writeln('<meta name="Generator" content="Microsoft Word 15">');
    content.writeln('<meta name="Originator" content="Microsoft Word 15">');
    content.writeln('<title>题目导出</title>');
    content.writeln('<!--[if gte mso 9]>');
    content.writeln('<xml>');
    content.writeln('<w:WordDocument>');
    content.writeln('<w:View>Print</w:View>');
    content.writeln('<w:Zoom>100</w:Zoom>');
    content.writeln('<w:DoNotOptimizeForBrowser/>');
    content.writeln('</w:WordDocument>');
    content.writeln('</xml>');
    content.writeln('<![endif]-->');
    content.writeln('<style>');
    content.writeln('<!-- /* 样式定义 */');
    content.writeln('body { font-family: "宋体", SimSun, serif; font-size: 12pt; line-height: 1.5; }');
    content.writeln('h1 { font-size: 18pt; font-weight: bold; text-align: center; margin: 20pt 0; }');
    content.writeln('h2 { font-size: 14pt; font-weight: bold; margin: 10pt 0; }');
    content.writeln('p { margin: 10pt 0; }');
    content.writeln('.question { margin-bottom: 15pt; }');
    content.writeln('.question-title { font-weight: bold; }');
    content.writeln('.options { margin-left: 20pt; }');
    content.writeln('.answer { font-weight: bold; color: #009900; }');
    content.writeln('.explanation { margin-left: 20pt; color: #0000FF; }');
    content.writeln('img { max-width: 90%; display: block; margin: 10pt 0; }');
    content.writeln('-->');
    content.writeln('</style>');
    content.writeln('</head>');
    content.writeln('<body>');
    
    // 添加标题
    String title;
    // 根据题目类型设置标题
    if (questions.isNotEmpty) {
      String modulePrefix = '';
      String type = questions[0].type;
      
      // 根据题目类型确定模块名称前缀
      switch (type) {
        case 'logical_reasoning':
          modulePrefix = '逻辑推理';
          break;
        case 'quantitative_relation':
          modulePrefix = '数量关系';
          break;
        case 'politics':
          modulePrefix = '时政';
          break;
        case 'common_sense':
          modulePrefix = '常识';
          break;
        case 'verbal_comprehension':
          modulePrefix = '言语理解';
          break;
        case 'data_analysis':
          modulePrefix = '资料分析';
          break;
        default:
          modulePrefix = '';
          break;
      }
      
      // 根据模块名称和导出类型设置标题
      if (modulePrefix.isNotEmpty) {
        title = exportType == WordExportType.questionsOnly ? '$modulePrefix题目练习' : '$modulePrefix题目练习（含答案与解析）';
      } else {
        title = exportType == WordExportType.questionsOnly ? '题目练习' : '题目练习（含答案与解析）';
      }
    } else {
      title = exportType == WordExportType.questionsOnly ? '题目练习' : '题目练习（含答案与解析）';
    }
    content.writeln('<h1>$title</h1>');
    
    // 添加题目内容
    for (int i = 0; i < questions.length; i++) {
      Question question = questions[i];
      
      content.writeln('<div class="question">');
      content.writeln('<p class="question-title">${i + 1}. ${_escapeHtml(question.question)}</p>');
      
      // 添加题目图片
      if (question.questionImageUrl != null && question.questionImageUrl!.isNotEmpty) {
        String processedImagePath = await _processImagePath(question.questionImageUrl);
        if (processedImagePath.isNotEmpty) {
          content.writeln('<p><img src="${processedImagePath}" alt="题目图片" /></p>');
        }
      }
      
      // 添加选项
      content.writeln('<div class="options">');
      content.writeln('<p>A. ${_escapeHtml(question.optionA)}</p>');
      // 添加选项A图片
      if (question.optionAImageUrl != null && question.optionAImageUrl!.isNotEmpty) {
        String processedImagePath = await _processImagePath(question.optionAImageUrl);
        if (processedImagePath.isNotEmpty) {
          content.writeln('<p><img src="${processedImagePath}" alt="选项A图片" /></p>');
        }
      }
      
      content.writeln('<p>B. ${_escapeHtml(question.optionB)}</p>');
      // 添加选项B图片
      if (question.optionBImageUrl != null && question.optionBImageUrl!.isNotEmpty) {
        String processedImagePath = await _processImagePath(question.optionBImageUrl);
        if (processedImagePath.isNotEmpty) {
          content.writeln('<p><img src="${processedImagePath}" alt="选项B图片" /></p>');
        }
      }
      
      content.writeln('<p>C. ${_escapeHtml(question.optionC)}</p>');
      // 添加选项C图片
      if (question.optionCImageUrl != null && question.optionCImageUrl!.isNotEmpty) {
        String processedImagePath = await _processImagePath(question.optionCImageUrl);
        if (processedImagePath.isNotEmpty) {
          content.writeln('<p><img src="${processedImagePath}" alt="选项C图片" /></p>');
        }
      }
      
      content.writeln('<p>D. ${_escapeHtml(question.optionD)}</p>');
      // 添加选项D图片
      if (question.optionDImageUrl != null && question.optionDImageUrl!.isNotEmpty) {
        String processedImagePath = await _processImagePath(question.optionDImageUrl);
        if (processedImagePath.isNotEmpty) {
          content.writeln('<p><img src="${processedImagePath}" alt="选项D图片" /></p>');
        }
      }
      content.writeln('</div>');
      
      // 如果需要包含答案和解析
      if (exportType == WordExportType.questionsWithAnswers) {
        content.writeln('<p class="answer">正确答案: ${question.correctAnswer}</p>');
        if (question.explanation.isNotEmpty) {
          content.writeln('<p class="explanation">解析: ${_escapeHtml(question.explanation)}</p>');
          // 添加解析图片
          if (question.explanationImageUrl != null && question.explanationImageUrl!.isNotEmpty) {
            String processedImagePath = await _processImagePath(question.explanationImageUrl);
            if (processedImagePath.isNotEmpty) {
              content.writeln('<p><img src="${processedImagePath}" alt="解析图片" /></p>');
            }
          }
        }
      }
      
      content.writeln('</div>');
      
      // 添加分隔线，除了最后一题
      if (i < questions.length - 1) {
        content.writeln('<hr/>');
      }
    }
    
    // 添加Word文档尾部
    content.writeln('</body>');
    content.writeln('</html>');
    
    return content.toString();
  }
  
  // HTML转义
  static String _escapeHtml(String text) {
    return text
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;')
        .replaceAll("'", '&#39;');
  }
  
  // 处理图片路径，如果是本地文件则转换为Base64编码，并调整图片大小
  static Future<String> _processImagePath(String? imagePath) async {
    if (imagePath == null || imagePath.isEmpty) {
      return '';
    }
    
    try {
      // 检查是否是网络图片
      if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
        return imagePath; // 返回原始URL
      }
      
      // 处理本地文件路径
      File imageFile = File(imagePath);
      if (await imageFile.exists()) {
        // 读取文件内容
        Uint8List bytes = await imageFile.readAsBytes();
        
        // 使用image包处理图片缩放
        try {
          // 解码图片
          img.Image? image = img.decodeImage(bytes);
          if (image != null) {
            // 计算新的尺寸，保持宽高比
            int maxWidth = 300; // 最大宽度，降低到300
            int maxHeight = 250; // 最大高度，降低到250
            int newWidth = image.width;
            int newHeight = image.height;
            
            // 始终进行缩放以减小图片大小
            double widthRatio = maxWidth / newWidth;
            double heightRatio = maxHeight / newHeight;
            double ratio = widthRatio < heightRatio ? widthRatio : heightRatio;
            
            // 如果图片已经很小，仍然缩小到原来的30%
            if (ratio > 1.0) {
              ratio = 0.3;
            }
            
            newWidth = (newWidth * ratio).round();
            newHeight = (newHeight * ratio).round();
            
            // 调整图片大小
            image = img.copyResize(image, width: newWidth, height: newHeight);
            
            // 重新编码图片
            if (imagePath.toLowerCase().endsWith('.png')) {
              // 对PNG使用量化压缩以减小体积
              bytes = Uint8List.fromList(img.encodePng(image, level: 9));
            } else {
              // 对于JPEG和其他格式，使用JPEG编码，并极大降低质量
              bytes = Uint8List.fromList(img.encodeJpg(image, quality: 30));
            }
          }
        } catch (e) {
          print('图片缩放失败: $e');
          // 如果缩放失败，继续使用原始图片
        }
        
        // 确定MIME类型
        String mimeType = 'image/jpeg'; // 默认JPEG
        if (imagePath.toLowerCase().endsWith('.png')) {
          mimeType = 'image/png';
        } else if (imagePath.toLowerCase().endsWith('.gif')) {
          mimeType = 'image/gif';
        } else if (imagePath.toLowerCase().endsWith('.svg')) {
          mimeType = 'image/svg+xml';
        }
        
        // 转换为Base64
        String base64Image = base64Encode(bytes);
        return 'data:$mimeType;base64,$base64Image';
      }
    } catch (e) {
      print('处理图片失败: $e');
    }
    
    return imagePath; // 如果处理失败，返回原始路径
  }
}